package com.yuyou.tas.lesson.service.impl;


import com.yuyou.tas.lesson.mapper.BaseLevelMapper;
import com.yuyou.tas.lesson.mapper.LessonMapper;
import com.yuyou.tas.lesson.service.IBaseLevelService;
import com.yuyou.tas.service.api.admin.entity.AuthOrganization;
import com.yuyou.tas.service.api.admin.service.AuthOrganAPI;
import com.yuyou.tas.service.api.lesson.dto.DtoBaseLevel;
import com.yuyou.tas.service.api.lesson.entity.BaseLevel;
import com.yuyou.tas.service.api.lesson.entity.Lesson;
import com.yuyou.tas.service.api.report.entity.ExamModel;
import com.yuyou.tas.service.api.report.service.ExamModelAPI;
import com.yuyou.tas.util.bean.LoginRedisObj;
import com.yuyou.tas.util.bean.Pagination;
import com.yuyou.tas.util.bean.ResBoolSimpleInfo;
import com.yuyou.tas.util.enums.lesson.LessonBaseEnums;
import com.yuyou.tas.util.enums.lesson.LessonEnums;
import com.yuyou.tas.util.exception.BusinessException;
import com.yuyou.tas.util.tool.BeanUtils;
import com.yuyou.tas.util.tool.Sequence;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;

@Service
public class BaseLevelServiceImpl implements IBaseLevelService {

    @Autowired
    private BaseLevelMapper mapper;

    @Autowired
    private LessonMapper lessonMapper;

    @Autowired
    private ExamModelAPI examModelAPI;

    @Autowired
    private AuthOrganAPI authOrganAPI;


    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo addLevel(String name, Integer isTan,Long pId, LoginRedisObj user,Long organId) {
        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"插入成功");
        BaseLevel bl = new BaseLevel();
        bl.setId(Sequence.getSequence().nextId());
        bl.setName(name);
        bl.setAuthOrganizationId(organId);
        bl.setCreateTime(new Date());
        bl.setCreateUser(user.getUserId());
        bl.setIsStan(isTan);
        bl.setIsUse(LessonBaseEnums.isEnableed.enabl.getValue());//默认启用
        bl.setpId(pId);
        bl.setValue(bl.getId());

        //获取最大code值
        Map<String, Object> condion = new HashMap<>();
        String defaultCode = "1";
        condion.put("organ_id",organId);
        condion.put("isUse","1");
        if(!user.getIsSystem()){//机构管理员
            defaultCode = "100";
            condion.put("isStan","0");
        }
        Long maxCode = mapper.findMaxCode(condion);
        bl.setCode(maxCode != 0 ? (maxCode+1)+"":defaultCode);

        mapper.insert(bl);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo updateLevel(Long id, String name,Long pId, Integer isTan, LoginRedisObj user) {
        //根据code和机构id获取班型
        Map<String , Object> conditon = new HashMap<>();
        conditon.put("code",id);
        conditon.put("organ_id",user.getOrganizationId());
        List<BaseLevel> list = mapper.findLevels(conditon);
        if(CollectionUtils.isEmpty(list)){
            throw new BusinessException("删除失败，找不到该班型");
        }else{
            id = list.get(0).getId();
        }

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"更新成功");
        BaseLevel bl = new BaseLevel();
        bl.setId(id);
        bl.setName(name);
        bl.setIsStan(isTan);
        if(pId != null){
            bl.setpId(pId);
        }
        mapper.updateByPrimaryKeySelective(bl);

        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public ResBoolSimpleInfo delLevel(Long id , LoginRedisObj user) {
        //根据code和机构id获取班型
        Map<String , Object> conditon = new HashMap<>();
        conditon.put("code",id);
        conditon.put("organ_id",user.getOrganizationId());
        List<BaseLevel> list = mapper.findLevels(conditon);
        if(CollectionUtils.isEmpty(list) || list.get(0) == null){
            throw new BusinessException("删除失败，找不到该班型");
        }else if(list.get(0).getpId() != null){
            throw new BusinessException("标准班型，不能删除！");
        }

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,"删除成功");

        List<Lesson> ls = lessonMapper.selectByLevel(id , user.getOrganizationId());
        if(!CollectionUtils.isEmpty(ls)){//已被课程引用
            final List<String> existList = new ArrayList<>();
            ls.stream().limit(3).forEach(l -> existList.add(l.getName()));
            throw new BusinessException("无法删除，该班型已经被["+String.join(",",existList)+"]课程引用");
        }

        //判断是否被试卷模版引用
        List<ExamModel> examModels = examModelAPI.selectModelByTrimester(id);
        if(!CollectionUtils.isEmpty(examModels)){//已被班级引用
            final List<String> existList = new ArrayList<>();
            examModels.stream().limit(3).forEach(e -> existList.add(e.getName()));
            if(examModels.size() > 3){
                throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]等"+examModels.size()+"个课程引用");
            }else{
                throw new BusinessException("无法删除，该学期已经被["+String.join(",",existList)+"]课程引用");
            }
        }

        mapper.deleteByPrimaryKey(list.get(0).getId());

        return info;
    }

    @Override
    public ResBoolSimpleInfo<BaseLevel> getLevelByID(Long id) {
        BaseLevel bl = mapper.selectByPrimaryKey(id);

        ResBoolSimpleInfo info = new ResBoolSimpleInfo(true,null , bl);
        return info;
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public int findLevelCount(Pagination<DtoBaseLevel> queryPgn) {
        return mapper.findLevelCount(queryPgn);
    }

    @Override
    @Transactional(rollbackFor=Exception.class,timeout=60)
    public List<DtoBaseLevel> findLevelPageList(Pagination<DtoBaseLevel> queryPgn) {
        List<DtoBaseLevel> list = mapper.findLevelPageList(queryPgn);
        list.forEach(dtoBaseLevel -> {
            if(dtoBaseLevel.getpId() == null || dtoBaseLevel.getpId().equals("")){
                dtoBaseLevel.setIsStandard(0);
            }else {
                dtoBaseLevel.setIsStandard(1);
            }
        });
        return list;
    }

    @Override
    public BaseLevel selectByPKandOrgan(Long id, Long authOrganizationId) {
        return mapper.selectByPKandOrgan(id, authOrganizationId);
    }

    @Override
    public List<Long> findByIds(Set<Long> ids) {
        List<Long> list = new ArrayList<>();
        if (ids != null && ids.size() > 0){
            Map<String , Object> condtion = new HashMap<>();
            condtion.put("ids",ids);
            condtion.put("is_stan", LessonEnums.type.defind.getValue());
            list = mapper.findByIds(condtion);
        }
        return list;
    }

    @Override
    public BaseLevel findById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public List<BaseLevel> findBaseLevelByOrganId(Long organId) {
        //根据code和机构id获取班型
        Map<String , Object> conditon = new HashMap<>();
        conditon.put("organ_id", organId);
        List<BaseLevel> list = mapper.findLevels(conditon);
        return list;
    }

    @Override
    public void sycnLevel(String code, Long organId) {
        //根据code和机构id获取班型
        Map<String , Object> conditon = new HashMap<>();
        conditon.put("code",code);
        conditon.put("organ_id",organId);
        List<BaseLevel> list = mapper.findLevels(conditon);

        if(!CollectionUtils.isEmpty(list) && list.get(0) != null){
            BaseLevel b = list.get(0);
            //获取全部机构
            List<AuthOrganization> organs = authOrganAPI.selectAll();
            if(!CollectionUtils.isEmpty(organs)){
                organs.forEach(o -> {
                    if(!o.getId().equals(organId)){
                        BaseLevel newOne = new BaseLevel();
                        BeanUtils.copyProperties(newOne , b);
                        newOne.setAuthOrganizationId(o.getId());
                        newOne.setId(Sequence.getSequence().nextId());
                        newOne.setCreateTime(new Date());
                        newOne.setCreateUser(null);
                        newOne.setpId(Long.valueOf(b.getCode()));
                        newOne.setValue(newOne.getId());
                        mapper.insert(newOne);
                    }
                });
            }


        }else{
            throw new BusinessException("没找到对应的班型");
        }
    }

    @Override
	public BaseLevel selectByCode7Organ(String code, Long authOrganizationId) {
		return mapper.selectByCode7Organ(code, authOrganizationId);
	}
}